const {checkToken} = require('../utils/token')

// 验证token是否有效
const verifyToken = async (ctx, next) => {
  // 1.获取token
  const authorization = ctx.headers.authorization
  if (!authorization) {
    ctx.throw(403, "没有传token")
  }
  
  // 2.验证token
  try {
    const token = authorization.replace("Bearer ", "")
    const res = checkToken(token)
    ctx.user = res
    await next()
  } catch (error) {
    ctx.throw(403, error.sqlMessage || error || "错误/过期的token")
  }
}

module.exports = {
  verifyToken
}
